<?php
namespace App\Controller;

use lib\View;
use App\Model\Gallery;

class ImageController 
{
	public function edit()
	{
		$gid = $this->input('g');
		$id = $this->input('m');

		$gallery = Gallery::find(['id' => $gid]);

		$image = null;
		foreach ($gallery->imageCollection as $img) {
			if ($img->id === $id) {
				$image = $img;
				break;
			}
		}

		return new View('image/edit', ['image' => $image]);
	}

	public function update()
	{
		$gid = $this->input('g');
		$id = $this->input('m');

		$title = $this->input('title');
		$description = $this->input('description');

		$gallery = Gallery::find(['id' => $gid]);

		$image = null;
		for ($i = 0; $i < count($gallery->imageCollection); $i++) {
			if ($gallery->imageCollection[$i]->id === $id) {
				$gallery->imageCollection[$i]->title = $title;
				$gallery->imageCollection[$i]->description = $description;
				break;
			}
		}
		$gallery->save();
		header('Location:' . url('gallery/detail', ['id' => $gid]));
	}

	public function destroy()
	{
		$gid = $this->input('g');
		$id = $this->input('m');

		$gallery = new Gallery();
		$gallery->destroy($gid,$id);

		header('Location:' . url('gallery/detail',['id' => $gid]));
	}

	// 退出登录
	public function logout()
	{
		unset($_SESSION['user']);

		header('Location:' . url('index'));
	}

	private function input($name)
           {
           	          return htmlspecialchars(stripslashes($_REQUEST[$name]));
           }
}